<template>
  <div class="registerForm">
    <!-- 表单区域 -->
    <el-form :model="form" :rules="rules" ref="registerForm" class="demo-ruleForm">
      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input
          v-model="form.username"
          placeholder="请输入用户名"
          clearable
          @focus="cleanValid('username')"
        ></el-input>
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item prop="captcha">
        <el-input placeholder="验证码" v-model="form.captcha" @focus="cleanValid('captcha')">
          <template slot="append">
            <el-button type="info" @click="sendCaptcha">发送验证码</el-button>
          </template>
        </el-input>
      </el-form-item>
      <!-- 昵称 -->
      <el-form-item prop="nickname">
        <el-input
          v-model="form.nickname"
          placeholder="昵称"
          clearable
          @focus="cleanValid('nickname')"
        ></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="form.password"
          autocomplete="off"
          placeholder="输入密码"
          @focus="cleanValid('password')"
        ></el-input>
      </el-form-item>
      <!-- 确认密码 -->
      <el-form-item prop="checkPass">
        <el-input
          type="password"
          v-model="form.checkPass"
          autocomplete="off"
          placeholder="确认密码"
          @focus="cleanValid('checkPass')"
        ></el-input>
      </el-form-item>
      <!-- 注册按钮 -->
      <el-button type="primary" style="width:100%" @click="register">注册</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    //   确认密码的判断处理
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    // var validatePass = (rule, value, callback) => {
    //   // 使用promise方法 进行判断
    //   return new Promise((resolve, reject) => {
    //     if (value === '') {
    //       reject(new Error('密码不能为空'))
    //     } else if (value != this.form.password) {
    //       reject(new Error('两次密码输入不一致'))
    //     } else {
    //       resolve()
    //     }
    //   })
    // };
    return {
      form: {
        username: '',
        password: '',
        checkPass: '',   //确认密码
        captcha: '',     //验证码
        nickname: '',
      },
      //定义验证规则 rules定义在data中，它是一个对象
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          //补充正则验证
          { pattern: /^1\d{10}$|^\w{3,}$/, message: '用户名不少于3个字符或11位数字', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { pattern: /^\w{3,}$/, message: '密码不少于3个数字或字母', trigger: 'blur' }
        ],
        captcha: [  //验证码
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }, 1
        ],
        checkPass: [  //确认密码
          { validator: validatePass, trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    // 清除验证
    cleanValid(propname) {
      // 传入 prop属性的值，清除指定的验证
      this.$refs.registerForm.clearValidate(propname);
    },
    //发送验证码     
    // 步骤--要发送手机号给后台，后台生成验证码，后台发手机号和验证码给运营商；运营商将验证码发给对应的手机号
    sendCaptcha() {
      //先判断手机号是否正确，只有手机号正确，才发请求
      if (/^1\d{10}$/.test(this.form.username)) {
        this.$axios({
          method: 'post',
          url: '/captchas',
          data: { tel: this.form.username }
        }).then(res => {
          console.log(res);
          this.$confirm('你本次的验证码是' + res.data.code, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success'
          });
        });
      } else {
        //确认框提示
        this.$confirm('输入的手机号格式不正确', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
      }
    },
    //注册
    register() {
      // 发送请求
      //由于后台要求的是四个参数，而this.form有五个参数（多了checkPass）
      let { checkPass, ...props } = this.form    //es6语法解构，获取form中除了checkPass属性的值
      console.log(props);
      this.$axios({
        method: 'post',
        url: '/accounts/register',
        data: props
      }).then(res => {
        console.log(res);
        this.$message.success('注册成功')       //换弹确认框也可
      }).then(() => {    //这里需要加个.then，我要弹出消息，再跳转
        //自动切换到登录
        this.$emit('goLogin')
      })
      //错误处理
      // .catch(err=>{
      //   console.dir(err)
      // if(err.response.data.statusCode == 400){
      //   this.$message.error(err.response.data.message)
      // }
      // })
    }
  }
}
</script>

<style lang="less" scoped>
.registerForm {
  padding: 30px;
}
</style>